---@class BindableField : LuaObject
---@field _isForce boolean
---@field _value any
---@field _oldValue any
---@field _events LuaAction[]
---@return BindableField
local this = BaseClass("BindableField")

function this:GetValue()
    return self._value
end

---@param value any
function this:SetValue(value)
    if self._isForce or self._value ~= value then
        self._oldValue = self._value --缓存旧的值
        self._value = value --刷新新的值
        this.Publish(self)
    end
end

---Subscribe:订阅
---@param luaAction LuaAction 回调方法 参数:先前的值，现在的值
function this:Subscribe(luaAction)
    table.insert(self._events, luaAction)
end

---取消订阅
---@param luaAction LuaAction 回调方法 参数:先前的值，现在的值
function this:Unsubscribe(luaAction)
    local idx = table.keyof(self._events, luaAction, -1)
    table.remove(self._events, idx)
end

---是否已经绑定过某个事件
---@param luaAction LuaAction 订阅的函数
function this:IsSubscribe(luaAction)
    return table.contains(self._events, luaAction)
end

---发布订阅
function this:Publish()
    local oldValue = self._oldValue
    local newValue = self._value

    for key, value in pairs(self._events) do
        value(oldValue, newValue)
    end
end

---设置强制刷新
---@param value any
function this:SetIsForce(value)
    self._isForce = value
end

---清空所有订阅
function this:Clear()
    table.clear(self._events)
    self._oldValue = nil
    self._value = nil
end

---构造函数
function this:__ctor()
    self._events = {}
    self._isForce = false
end

BindableField = this